package com.zx.freeapi.exception;

import com.zx.freeapi.common.BaseResponse;
import com.zx.freeapi.common.ResultUtils;
import com.zx.freeapi.model.enums.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public BaseResponse<?> businessExceptionHandler(BusinessException e) {
        log.error("businessException: " + e.getMessage(), e);
        return ResultUtils.error(e.getCode(), e.getMessage());
    }
    @ExceptionHandler(DuplicateKeyException.class)
    public BaseResponse<?> duplicateKeyExceptionHandler(DuplicateKeyException e) {
        log.error("duplicateKeyException", e);
        if (e.getCause() instanceof SQLIntegrityConstraintViolationException) {
            SQLIntegrityConstraintViolationException sqlException = (SQLIntegrityConstraintViolationException) e.getCause();
            if (sqlException.getMessage().contains("Duplicate entry")) {
                String[] split = sqlException.getMessage().split(" ");
                String msg = split[2] + "已经存在";
                return ResultUtils.error(ErrorCode.SYSTEM_ERROR, msg);
            }
        }
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "未知错误");
    }

    @ExceptionHandler(RuntimeException.class)
    public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
        log.error("runtimeException", e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "系统错误");
    }

}